package com.micro.service.auth.server.config.security;


import com.micro.service.account.share.dto.UserBaseDto;
import com.micro.service.account.share.service.UserBaseService;
import com.micro.service.auth.server.model.User;
import com.micro.service.common.dto.ResultDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.social.security.SocialUser;
import org.springframework.social.security.SocialUserDetails;
import org.springframework.social.security.SocialUserDetailsService;
import org.springframework.stereotype.Service;

/**
 * @author xiucai
 * @description
 * @date 2018/11/21 0021 20:52
 */
@Service
@Slf4j
public class MyUserDetailsServiceImpl implements UserDetailsService,SocialUserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserBaseService userBaseService;

    @Override
    public UserDetails loadUserByUsername(String s) {
        log.info("用户登录传参==" + s);
        long begin = System.currentTimeMillis();

        ResultDTO<UserBaseDto> resultDTO = userBaseService.selectByMobile(s);
        UserBaseDto userBaseDto = resultDTO.getData();
        if(userBaseDto == null){
            log.error("帐号未找到=" + s);
            throw new UsernameNotFoundException("帐号未找到=" + s);
        }
        long end = System.currentTimeMillis();
        long execuTime = end - begin;
        log.info("====================查询用户耗时："+execuTime+"毫秒==============================");

        //校验用户是否被锁定等
        return new User(userBaseDto.getId(),userBaseDto.getName(),userBaseDto.getPassword(),userBaseDto.getHeadImg(),userBaseDto.getMobile());
    }



    @Override
    public SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException {
        //社交登录查询用户信息
        log.info("userId:"+userId);
        return buildUser(userId);
    }

    private SocialUserDetails buildUser(String userId) {

        String password = passwordEncoder.encode("123456");
        return new SocialUser(userId,password,
                true,true,true,true,
                AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
    }



}
